<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd">{{ $t('btn.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="shoppingCart" @click="handleAddCart()" :disabled="!currentRow">加入购物车</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      highlightCurrentRow
      border
      stripe
      @current-change="handleCurrentChange"
      v-dragable="[
        {
          selector: 'thead tr',
          option: {
            animation: 150,
            draggable: '.dragable-col',
            onEnd: (evt) => {
              const startIndex = 0
              const oldIndex = evt.oldIndex - startIndex
              const newIndex = evt.newIndex - startIndex
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex])
                columns.splice(oldIndex + 1, 1)
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex])
                columns.splice(oldIndex, 1)
              }
            }
          }
        }
      ]">
      <template v-for="col in columns">
        <el-table-column
          :key="col['prop']"
          :type="col['type']"
          :prop="col['prop']"
          :label="col['label']"
          :width="col['width']"
          :align="col['align']"
          :min-width="col['min-width']"
          :class-name="col['class-name']"
          :show-overflow-tooltip="col['show-overflow-tooltip']"
          v-if="!!col['visible']">
          <template #default="scope" v-if="col['custom-template']">
            <component :is="col['custom-template'](scope)"></component>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="600px" appendToBody draggable>
      <el-form ref="formRef" :model="form" labelWidth="120px">
        <el-row>
          <el-col :lg="24">
            <el-form-item label="纪念品名称" prop="name">
              <el-input v-model="form.name" readonly />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="单价" prop="price">
              <el-input v-model="form.price" readonly />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :max="form.stock" @change="handleQuantityChange" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="总价" prop="totalPrice">
              <span>￥{{ form.totalPrice }}元</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { vDragable } from 'element-plus-table-dragable'
import { useI18n } from 'vue-i18n'
import { ElInputNumber, ElMessageBox, FormInstance } from 'element-plus'
import { deepClone, getFormData } from '@/utils'
import modal from '@/plugins/modal'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
import { updateCart, deleteCart, getCartWithPage } from '@/api/souvenir/cart'
import { getOrderWithPage } from '@/api/souvenir/order'
const userStore = useUserStore()
const { t } = useI18n()
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadImgUrl = ref(baseUrl + import.meta.env.VITE_APP_UPLOAD_URL)
const headers = ref({ Authorization: 'Bearer ' + getToken() })
interface dictOption {
  dictLabel: string
  dictValue: string
}
const statusOptions = ref<dictOption[]>([
  { dictLabel: '在售', dictValue: '1' },
  { dictLabel: '下架', dictValue: '2' }
])
const loading = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userId: userStore.userId
})
interface product {
  id?: number
  imageUrl: string
  name: string
  detail: string
  price: number
  quantity: number
  status: string
  imageId?: number
  categoryId?: number
}
const list = ref<product[]>()
interface column {
  label?: string
  prop?: string
  type?: string
  width?: string
  align?: string
  'min-width'?: string
  'class-name'?: string
  'show-overflow-tooltip'?: boolean
  'custom-template'?: (scope: any) => {}
  visible: boolean
}
const columns = ref<column[]>([
  {
    prop: 'orderItems',
    type: 'expand',
    visible: true,
    'custom-template': (scope) => {
      return (
        <el-table data={scope.row.orderItems} border stripe>
          <el-table-column label="图片" align="center" width="80">
            {{
              default: (scope) => {
                return (
                  <>
                    <el-image
                      preview-teleported
                      src={scope.row.imageUrl}
                      preview-src-list={[scope.row.imageUrl]}
                      hide-on-click-modal
                      fit="contain"
                      lazy
                      class="el-avatar">
                      {{
                        error: () => {
                          return (
                            <>
                              <el-icon>
                                <Picture />
                              </el-icon>
                            </>
                          )
                        }
                      }}
                    </el-image>
                  </>
                )
              }
            }}
          </el-table-column>
          <el-table-column label="纪念品名称" prop="productName" />
          <el-table-column label="分类名称" prop="categoryName" />
          <el-table-column label="纪念品详情" prop="productDetail" />
          <el-table-column label="购买单价" prop="currentUnitPrice" />
          <el-table-column label="购买数量" prop="quantity" />
          <el-table-column label="购买总价" prop="totalPrice" />
        </el-table>
      )
    }
  },
  {
    prop: 'paymentTime',
    label: '购买时间',
    visible: true,
    'class-name': 'dragable-col'
  },
  {
    prop: 'payment',
    label: '订单总价',
    visible: true,
    'class-name': 'dragable-col'
  },
  {
    prop: 'action',
    label: '操作',
    align: 'center',
    width: '200',
    'custom-template': (scope) => {
      return (
        <>
          <el-button
            text
            icon="delete"
            type="danger"
            title={t('btn.delete')}
            onClick={() => {
              handleDelete(scope.row)
            }}></el-button>
        </>
      )
    },
    visible: true
  }
])
const title = ref('')
const open = ref(false)
const formRef = ref<FormInstance>()
const form = ref({
  name: '',
  price: 0,
  quantity: 0,
  totalPrice: 0,
  productId: 0,
  userId: userStore.userId,
  id: 0,
  stock: 0
})
const handleQuantityChange = (currentValue) => {
  form.value.totalPrice = form.value.price * currentValue
}
const handleUpdate = (row) => {
  title.value = '编辑数量'
  open.value = true
  formRef.value?.resetFields()
  reset(true, row)
  formRef.value?.clearValidate()
}
const handleDelete = async (row) => {
  try {
    await modal.confirm('是否要删除?')
    try {
      await deleteCart(row.id)
      modal.msgSuccess('删除成功')
    } catch (error) {
      console.error(error)
      modal.msgError('删除失败')
    }
    getList()
  } catch (error) {}
}
const handleAdd = () => {
  title.value = '新增纪念品'
  open.value = true
  formRef.value?.resetFields()
  reset(false)
  formRef.value?.clearValidate()
}
const reset = (isUpdate: boolean, row?: any) => {
  if (isUpdate) {
    form.value = deepClone(row)
    form.value.totalPrice = form.value.price * form.value.quantity
  } else {
    form.value = {
      name: '',
      price: 0,
      quantity: 0,
      totalPrice: 0,
      productId: 0,
      userId: userStore.userId,
      id: 0,
      stock: 0
    }
  }
}
const cancel = () => {
  open.value = false
  reset(false)
}
const handleConfirm = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const cartForm = ref({
          quantity: form.value.quantity,
          productId: form.value.productId,
          userId: form.value.userId,
          id: form.value.id
        })
        const { data } = await updateCart(cartForm.value)
        if (data) {
          modal.msgSuccess('编辑成功')
        }
      } catch (error) {
        console.error(error)
        modal.msgError('编辑失败')
      }
      open.value = false
      getList()
    }
  })
}
const currentRow = ref()
const handleCurrentChange = (val) => {
  currentRow.value = val
}

const handleAddOrder = async (row) => {
  try {
  } catch (error) {}
}

const getList = async () => {
  loading.value = true
  try {
    const { data } = await getOrderWithPage(queryParams.value)
    list.value = data.result
    total.value = data.totalNum
    loading.value = false
  } catch (error) {
    console.error(error)
    loading.value = false
  }
  loading.value = false
}
getList()
</script>

<style scoped></style>
